package com.zenglx.multilanguage.method;


import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.zenglx.multilanguage.metadata.ZlxTableInfo;
import com.zenglx.multilanguage.util.SqlHelper;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * SelectList 兼容MP原生方法
 */
public class SelectCount extends com.baomidou.mybatisplus.core.injector.methods.SelectCount {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        ZlxTableInfo zlxTableInfo = (ZlxTableInfo)tableInfo;
        if(zlxTableInfo.isMultiLanguage()) {
            SqlMethod sqlMethod = SqlMethod.SELECT_COUNT;
            String sql = String.format(sqlMethod.getSql(), sqlFirst(), sqlCount(),  SqlHelper.selectFromTableTl(tableInfo),
                    sqlWhereEntityWrapper(true, tableInfo), sqlComment());
            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
            return this.addSelectMappedStatementForOther(mapperClass, getMethod(sqlMethod), sqlSource, Integer.class);
        } else {
            return super.injectMappedStatement(mapperClass, modelClass, tableInfo);
        }

    }

    @Override
    protected String sqlWhereEntityWrapper(boolean newLine, TableInfo tableInfo) {
        ZlxTableInfo zlxTableInfo = (ZlxTableInfo)tableInfo;
        if(zlxTableInfo.isMultiLanguage()) {
            String sqlScript = zlxTableInfo.getAllSqlWhere(false, true, WRAPPER_ENTITY_DOT);
            sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", WRAPPER_ENTITY), true);
            sqlScript += NEWLINE;
            sqlScript += SqlScriptUtils.convertIf(String.format(SqlScriptUtils.convertIf(" AND", String.format("%s and %s", WRAPPER_NONEMPTYOFENTITY, WRAPPER_NONEMPTYOFNORMAL), false) + " ${%s}", WRAPPER_SQLSEGMENT),
                    String.format("%s != null and %s != '' and %s", WRAPPER_SQLSEGMENT, WRAPPER_SQLSEGMENT,
                            WRAPPER_NONEMPTYOFWHERE), true);
            sqlScript = SqlScriptUtils.convertWhere(sqlScript) + NEWLINE;
            sqlScript += SqlScriptUtils.convertIf(String.format(" ${%s}", WRAPPER_SQLSEGMENT),
                    String.format("%s != null and %s != '' and %s", WRAPPER_SQLSEGMENT, WRAPPER_SQLSEGMENT,
                            WRAPPER_EMPTYOFWHERE), true);
            sqlScript = SqlScriptUtils.convertIf(sqlScript, String.format("%s != null", WRAPPER), true);
            return newLine ? NEWLINE + sqlScript : sqlScript;
        } else {
            return super.sqlWhereEntityWrapper(newLine, tableInfo);
        }
    }

}
